####################################################################
#***2019 analysis
## Packages
# To install and open the R packages that you need for this code. 
need <- c('tidyverse','readstata13','lfe','glue','rdrobust', 'stargazer','arm', 'broom', 'ggplot2', 'dotwhisker', 'gridExtra')
have <- need %in% rownames(installed.packages()) 
if(any(!have)) install.packages(need[!have]) 
invisible(lapply(need, library, character.only=T)) 

# Change path to whereever you place the models
# To set up the working directory. 
script_folder = dirname(rstudioapi::getSourceEditorContext()$path)
setwd(glue('{script_folder}'))
rm(list = ls())
setwd("../")

## load in RD data:
load("5prepdata/final_rd_data.RData")

rd.data$previous_losses_count<-rd.data$times_run_ad-1 -rd.data$running_terms_served

main.specification <- function(x) {
  rd.data$cutoff<-NULL
  rd.data$bandwidth<-NULL
  rd.data$kw<-NULL
  
  y<-rdbwselect(x, rd.data$victory_marg, p=1, c = 0,  kernel = "tri", bwselect="mserd", covs = rd.data$year)
  rd.data$bandwidth<-y$bws[1]
  rm(y)
  
  # gen cutoff = 0
  rd.data$cutoff <- 0
  # gen kw = 1-(abs(cutoff-victory_marg))/bandwidth
  rd.data$kw <- 1-(abs(rd.data$cutoff-rd.data$victory_marg))/rd.data$bandwidth
  # replace kw = 0 if (victory_marg>cutoff+bandwidth | victory_marg<cutoff-bandwidth) 
  rd.data$kw[rd.data$victory_marg>(rd.data$cutoff+rd.data$bandwidth) | rd.data$victory_marg<(rd.data$cutoff-rd.data$bandwidth)] <- 0
  
  out <- felm(x[rd.data$kw>0] ~ won_election + victory_marg + f_x_win | year + const | 0 | const, data = rd.data[rd.data$kw>0,], weights = rd.data$kw[rd.data$kw>0])
  return(out)
}



m1<-main.specification(rd.data$dem)
m2<-main.specification(rd.data$rep)
m3<-main.specification(rd.data$term_length)
m4<-main.specification(rd.data$number_candidates)
m5<-main.specification(rd.data$sitting_incumbent)
m6<-main.specification(rd.data$running_terms_served)
m7<-main.specification(rd.data$gov_party_control)
m8<-main.specification(rd.data$unified_party_control)
m3<-main.specification(rd.data$previous_losses_count) #replacing term length with number of previous losses
summary(m9)

x1<- stargazer(list(m5, m6, m3,m4),
          title = "Test of sorting at the identifying threshold",
          style="apsr",
          font.size =  "scriptsize",
          model.numbers=T,
          # out="7tex/manuscript/tables/sourcefiles/TableX_ContinuityTests.tex",
          label = "tab:continuity",
          keep.stat=c("n","rsq"),
          dep.var.labels  = "Covariate tested:",
          column.labels=c("Is incumbent", "Number of terms served", "Number of previous losses", "Number of candidates"),
          keep = c("won_election"),
          covariate.labels = c("Won state legis. seat"),
          notes = "\\parbox[t]{.85\\linewidth}{Note: This table reports estimates of the effect of an additional state legislative term on individuals' career progression to Congressional candidacy. The dependent variable is equal to one if the candidate ever runs in the election listed in the column header and is zero otherwise. The sample contains all first-time state legislative elections within the optimal bandwidth given by the \\cite{CCT} algorithm. All regressions include state and election year fixed effects, a linear term for the vote margin and its interaction for having won the election, and the full set of candidate and election controls.  Standard errors clustered by state legislative constituency are reported in parentheses.}"
)


x2<- stargazer(list(m1,m2,m7,m8),
               title = "Test of sorting at the identifying threshold",
               style="apsr",
               font.size =  "scriptsize",
               model.numbers=T,
               # out="7tex/manuscript/tables/sourcefiles/TableX_ContinuityTests.tex",
               label = "tab:continuity",
               keep.stat=c("n","rsq"),
               dep.var.labels  = "Covariate tested:",
               column.labels=c( "Is Democrat", "Is Republican", "From governor's party", "From majority party"),
               keep = c("won_election"),
               covariate.labels = c("Won state legis. seat"),
               notes = "\\parbox[t]{.85\\linewidth}{Note: This table reports estimates of the effect of an additional state legislative term on individuals' career progression to Congressional candidacy. The dependent variable is equal to one if the candidate ever runs in the election listed in the column header and is zero otherwise. The sample contains all first-time state legislative elections within the optimal bandwidth given by the \\cite{CCT} algorithm. All regressions include state and election year fixed effects, a linear term for the vote margin and its interaction for having won the election, and the full set of candidate and election controls.  Standard errors clustered by state legislative constituency are reported in parentheses.}"
)

source("3analysis/starpanelSOC_diffLHS.R") 
star.panel.out <-   star_panel(x1, x2, panel.names = c("Incumbency and election characteristics ", "Party and party alignment"), extra.rows=0)
star.panel.out <- star.panel.out[!is.na(star.panel.out)]
star.panel.out
##write to a tex file and compile to check output
star_tex_write(star.panel.out, file = "7tex/manuscript/tables/sourcefiles/Table 2.tex", headers = FALSE)



